package org.example.io.multireactor;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MultiHandler implements Runnable{
    SocketChannel socket;
    ExecutorService executorService;

    public MultiHandler(SocketChannel socket){
        this.socket = socket;
        executorService = Executors.newCachedThreadPool();
    }
    @Override
    public void run() {
        executorService.submit(new Handler(socket));
    }

    private class Handler implements Runnable{
        private SocketChannel socket;

        public Handler(SocketChannel socket){
            this.socket = socket;
        }

        @Override
        public void run() {
            System.out.println("开始处理读请求，当前处理线程：" + Thread.currentThread());
            int len = 0, total = 0;
            StringBuilder msg = new StringBuilder();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            try {
                do {
                    len = socket.read(buffer);
                    if (len > 0) {
                        total += len;
                        msg.append(new String(buffer.array()));
                    }
                } while (len > buffer.capacity());
                System.out.println(socket.getRemoteAddress() + ": Server receive Msg:" + msg);
                System.out.println("total:" + total);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
